from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.orm import Session

from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

menu_router = APIRouter(prefix="/sys/sysPermission", tags=["菜单管理"])


class GetMenu(PaginationBase):
    sort: str = Field(default=None, description="排序字段")
    order: str = Field(default="desc", description="排序方式")
    pid: int = Field(default=None, description="上级菜单id")
    name: str = Field(default=None, description="菜单名称")
    systype: str = Field(default=None, description="系统别")


# todo 10.功能资料
@menu_router.get("/list", summary="查询菜单")
def get_sys_permission(menu: GetMenu = Query(), db: Session = Depends(get_db)):
    # 根据条件取出数据
    sql_3 = "select count(1) "
    sql_3 = sql_3 + " from am_sys_permission"
    sql_3 = sql_3 + " where 1=1"
    params = {}
    if menu.name is not None:
        sql_3 = sql_3 + " and name like concat('%',:menu_name ,'%')"
        params["menu_name"] = menu.name
    if menu.pid is not None:
        sql_3 = sql_3 + " and pid = :pid"
        params["pid"] = menu.pid
    # 2025.0.3.05 新增根据systype获取菜单
    if menu.systype is not None:
        sql_3 = sql_3 + " and systype = :systype"
        params["systype"] = menu.systype
    if menu.sort is not None and menu.order is not None:
        sql_3 = sql_3 + " order by  :sort  :order"
        params["sort"] = menu.sort
        params["order"] = menu.order
    count = db.execute(text(sql_3), params).scalar()

    # 根据条件取出数据
    sql_3 = "select id,pid,name,fname,yname,value,icon,type,uri,status,create_time"
    sql_3 = sql_3 + ",sort_seq,method,create_id,update_time,update_id,systype"
    sql_3 = sql_3 + " from am_sys_permission"
    sql_3 = sql_3 + " where 1=1"
    params = {}
    if menu.name is not None:
        sql_3 = sql_3 + " and name like concat('%',:menu_name ,'%')"
        params["menu_name"] = menu.name
    if menu.pid is not None:
        sql_3 = sql_3 + " and pid = :pid"
        params["pid"] = menu.pid
    # 2025.0.3.05 新增根据systype获取菜单
    if menu.systype is not None:
        sql_3 = sql_3 + " and systype = :systype"
        params["systype"] = menu.systype
    if menu.sort is not None and menu.order is not None:
        sql_3 = sql_3 + " order by  :sort  :order"
        params["sort"] = menu.sort
        params["order"] = menu.order

    sql_3 = sql_3 + " limit :limit offset :offset"
    params["offset"] = menu.offset
    params["limit"] = menu.limit

    data = db.execute(text(sql_3), params).fetchall()
    if data is None or len(data) == 0:
        return BaseResponse.success("查询结果为空")

    data_list = []
    for j1 in range(len(data)):
        data_dict = {}
        data_dict["id"] = int(data[j1][0])
        data_dict["pid"] = int(data[j1][1])
        data_dict["name"] = data[j1][2]
        data_dict["fname"] = data[j1][3]
        data_dict["yname"] = data[j1][4]
        data_dict["value"] = data[j1][5]
        data_dict["icon"] = data[j1][6]
        data_dict["type"] = data[j1][7]
        data_dict["uri"] = data[j1][8]
        data_dict["status"] = data[j1][9]
        data_dict["createtime"] = data[j1][10]
        data_dict["sortSeq"] = data[j1][11]
        data_dict["method"] = data[j1][12]
        data_dict["createid"] = data[j1][13]
        data_dict["updatetime"] = data[j1][14]
        data_dict["updateid"] = data[j1][15]
        data_dict["systype"] = data[j1][16]
        data_list.append(data_dict)

    info_dict = {"list": data_list,
                 "limit": menu.limit,
                 "page": menu.pageSize,
                 "pages": (count + menu.pageSize - 1) // menu.pageSize,
                 "total": count}
    return BaseResponse.success(data=info_dict)


class MenuCreate(BaseModel):
    id: int = Field(default=None, description="菜单id 修改时填入")
    fname: str = Field(default="", description="繁体名称")
    icon: str = Field(default="", description="图标地址")
    name: str = Field(description="菜单名称")
    pid: int = Field(default=0, description="上级菜单id")
    sortSeq: int = Field(default=1, description="排序")
    status: int = Field(default=1, description="启用状态 0.禁用 1.启用")
    type: int = Field(description="权限类型 0.目录 1.菜单 2.按钮")
    updateId: int = Field(default=None, description="更新人")
    uri: str = Field(default="", description="前端资源路径")
    value: str = Field(default="", description="权限值")
    yname: str = Field(default="", description="英文名称")
    method: str = Field(default="")
    systype: str = Field(default="S", description="系统别")


@menu_router.post("/create", summary="新建菜单")
def create_sys_permission(menu: MenuCreate, db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):
    try:
        user = EncryptionMiddleware.decrypt_token(token)
        user_id = user["user_id"]
        # 获取单号
        permission_id = ""
        sql = "select last_value+1  last_value from am_sys_permission_id_seq"
        res = db.execute(text(sql)).fetchall()
        permission_id = res[0][0]  # 出现问题
        menu.updateId = user_id

        sql = "insert into am_sys_permission(pid,name,value,icon,type,uri,status,create_time,sort_seq,method,create_id,update_time,update_id,fname,yname,systype)"
        sql = sql + " values( :pid,:name,:value,:icon,:type,:uri,:status,now(),:sort_seq,:method,:create_id,now(),:update_id,:fname,:yname,:systype)"
        result = db.execute(text(sql), {
            "pid": permission_id,
            "name": menu.name,
            "value": menu.value,
            "icon": menu.icon,
            "type": menu.type,
            "uri": menu.uri,
            "status": menu.status,
            "sort_seq": menu.sortSeq,
            "method": menu.method,
            "create_id": user_id,
            "update_id": menu.updateId,
            "fname": menu.fname,
            "yname": menu.yname,
            "systype": menu.systype
        })
        db.commit()
        if result is None:
            return BaseResponse.error()
        else:
            # 返回
            d1 = {}
            d1['id'] = permission_id
            d1['pid'] = menu.pid
            d1['name'] = menu.name
            d1['value'] = menu.value
            d1['icon'] = menu.icon
            d1['type'] = menu.type
            d1['uri'] = menu.uri
            d1['status'] = menu.status
            d1['createtime'] = None
            d1['sortseq'] = menu.sortSeq
            d1['method'] = menu.method
            d1['createid'] = menu.updateId
            d1['updatetime'] = None
            d1['updateid'] = menu.updateId
            d1['fname'] = menu.fname
            d1['yname'] = menu.yname

            d1['systype'] = menu.systype
            return BaseResponse.success(data=d1)
    except Exception as e:
        return BaseResponse.error(message="授权过期")


@menu_router.post("/update", summary="更新菜单信息")
def update_menu(menu: MenuCreate, token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
    try:
        user = EncryptionMiddleware.decrypt_token(token)
        user_id = user["user_id"]
        menu.updateId = user_id
    except Exception as e:
        return BaseResponse.error(message="授权已失效")

    sql = "update am_sys_permission"
    sql = sql + " set name= :name,pid= :pid,sort_seq=:sort_seq,status=:status,type=:type,uri=:uri,"
    sql = sql + "value= :value ,yname=:yname,method=:method,update_time=now(),update_id=:update_id"
    if menu.systype != "":
        sql = sql + ",systype= :systype "
    sql = sql + " where id= :id"
    i = db.execute(text(sql), {
        "id": menu.id,
        "name": menu.name,
        "pid": menu.pid,
        "sort_seq": menu.sortSeq,
        "status": menu.status,
        "type": menu.type,
        "uri": menu.uri,
        "value": menu.value,
        "yname": menu.yname,
        "method": menu.method,
        "update_id": menu.updateId,
        "systype": menu.systype
    })
    if i is None:
        return BaseResponse.error()
    else:
        db.commit()
        return BaseResponse.success()


@menu_router.post("/delete/{id}", summary="根据id删除菜单")
def delete_menu(id: int = Path(description="菜单id"), token: str = Depends(oauth2_scheme),
                db: Session = Depends(get_db)):
    try:
        user = EncryptionMiddleware.decrypt_token(token)
        user_id = user["user_id"]
        sql = "select count(1) from am_sys_permission where pid= :id"
        data = db.execute(text(sql), {"id": id}).scalar()
        if data > 0:
            return BaseResponse.error(message="有子菜单，不能删除")
        try:
            sql = "delete from am_sys_permission where id=:id"
            db.execute(text(sql), {"id": id})
            sql = "delete from am_sys_role_permission where permission_id= :id"
            db.execute(text(sql), {"id": id})
            db.commit()
            return BaseResponse.success()
        except Exception as e:
            db.rollback()
            return BaseResponse.error(message=str(e))
    except Exception as e:
        return BaseResponse.error(message="授权失效")
